package com.example.androidcomplete02.parser;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.R.integer;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import com.example.androidcomplete02.R;

public class Sax_parserAcitivity extends Activity {
	ListView list;
	ProgressDialog progressDlg;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch28_network_xmlparser);
		list = (ListView) findViewById(R.id.listView);
		new ParsingXml().execute("order.xml");
	}

	private class ParsingXml extends AsyncTask<String, Void, ArrayList<Item>> {
		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(Sax_parserAcitivity.this, "Wait",
					"xml parsing ...");
		}

		protected void onPostExecute(ArrayList<Item> result) {
			MyAdapter adapter = new MyAdapter(Sax_parserAcitivity.this, result);
			progressDlg.dismiss();
			list.setAdapter(adapter);
		}

		protected ArrayList<Item> doInBackground(String... params) {
			StringBuilder sb = new StringBuilder();
			String str = null;

			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						openFileInput(params[0])));
				while ((str = br.readLine()) != null) {
					sb.append(str);
				}
				br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return parsingXml(sb.toString());
		}
	}

	public ArrayList<Item> parsingXml(String xml) {

		final ArrayList<Item> arItem = new ArrayList<Item>();

		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser;
		try {
			parser = factory.newSAXParser();
			XMLReader reader = parser.getXMLReader();
			reader.setContentHandler(new DefaultHandler() {

				boolean initItem = false;
				Item itemClass;

				@Override
				public void startDocument() throws SAXException {
					super.startDocument();
					Log.d("SAX", "startDocument");
				}

				@Override
				public void endDocument() throws SAXException {
					super.endDocument();
					Log.d("SAX", "endDocument");
				}

				@Override
				public void startElement(String uri, String localName,
						String qName, Attributes attributes)
						throws SAXException {
					super.startElement(uri, localName, qName, attributes);
					String str = "uri: " + uri + " localName: " + localName
							+ " qName: " + qName + " Attributes: " + attributes;
					Log.d("SAX", "startElement" + str);
					if (localName.equalsIgnoreCase("item")) {
						initItem = true;
						itemClass = new Item();
					}
					
					if(attributes.getLength()>0){
						for(int i = 0; i<attributes.getLength(); i++){
							if(attributes.getLocalName(i).equalsIgnoreCase("price")){
								itemClass.setItemPrice(Integer.parseInt(attributes.getValue(i)));
							}else{
								itemClass.setMakerName(attributes.getValue(i));
							}
						}		
					}
				}

				@Override
				public void endElement(String uri, String localName,
						String qName) throws SAXException {
					super.endElement(uri, localName, qName);
					String str = "uri: " + uri + " localName: " + localName
							+ " qName: " + qName;
					Log.d("SAX", "endElement" + str);
				}

				@Override
				public void characters(char[] ch, int start, int length)
						throws SAXException {
					super.characters(ch, start, length);
					String str = "ch: " + ch.toString() + " start: " + start
							+ " length: " + length;
					Log.d("SAX", "characters" + str);
					
					if(initItem){
						itemClass.setItemName(new String(ch, start, length));
						arItem.add(itemClass);
						initItem = false;
					}
				}

			});

			InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
			reader.parse(new InputSource(is));
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return arItem;
	}
}